Lesson 2: Styling Text and Colors
Text Properties
CSS provides a wide range of properties to style and control the appearance of text. Below are some of the most commonly used text-related properties:
-
font-family: Defines the font for an element.
p {
font-family: 'Arial', sans-serif;
} -
font-size: Specifies the size of the text. You can use different units like
px
,em
, or%
.h1 {
font-size: 32px;
} -
font-weight: Controls the thickness of the text (e.g.,
normal
,bold
, or numerical values like400
,700
).p {
font-weight: bold;
} -
text-align: Aligns the text horizontally (e.g.,
left
,center
,right
, orjustify
).h2 {
text-align: center;
} -
line-height: Adjusts the space between lines of text.
p {
line-height: 1.5;
} -
text-transform: Alters the text's capitalization (e.g.,
uppercase
,lowercase
, orcapitalize
).h1 {
text-transform: uppercase;
} -
letter-spacing: Increases or decreases the space between letters.
p {
letter-spacing: 2px;
}
Color Values and Backgrounds
CSS allows you to define colors in various ways. Here are the most common color formats:
-
Color Names: You can use predefined color names like
red
,blue
, orgreen
.h1 {
color: red;
} -
HEX Values: A six-character hexadecimal value, starting with a
#
, representing the color.h1 {
color: #3498db; /* light blue */
} -
RGB and RGBA: Represents colors using Red, Green, and Blue values, each ranging from 0 to 255. The
A
inRGBA
is for opacity (0 for transparent, 1 for fully opaque).h1 {
color: rgb(52, 152, 219);
}
p {
background-color: rgba(52, 152, 219, 0.5); /* semi-transparent */
} -
HSL and HSLA: Stands for Hue, Saturation, and Lightness, with
A
again representing opacity.h1 {
color: hsl(207, 71%, 53%);
}
CSS Units
When styling elements, you will encounter various units for properties like font size, padding, and margins. Here are the most common:
-
px (Pixels): A fixed unit that represents a single pixel on the screen.
p {
font-size: 16px;
} -
em: Relative to the font size of the element. For example,
2em
is twice the size of the current font.p {
font-size: 1.5em; /* 1.5 times the parent element's font size */
} -
rem: Relative to the root (html) font size, which is useful for maintaining consistent sizing across the site.
p {
font-size: 1.2rem;
} -
%: Relative to the parent element, often used for fluid layouts and responsive design.
div {
width: 80%;
}